﻿@using Abp.Extensions
@using FutureGoodsItem = FutureApp.Shop.GoodsItem
@model FutureApp.Web.Models.Shop.GoodsViewModel

@section Scripts{
    <script>
        !function ($) {
            var $$$ = function () {
                this.$box = $('.box');
                this.$form = $('form');
                this.service = abp.services.app.goods;
                this.localize = abp.localization.localize;
                this.cache = {};
            };
            $$$.prototype = {
                init: function () {
                    this.formSubmit();
                    this.binding();
                    this.initChosen();
                },
                initChosen: function () {
                    var self = this;

                    $("input[name='MouldId']").on('selected.bs.list.modal', function (evt, params) {
                        var $sender = $(evt.currentTarget);
                        var data = $sender.data();
                        var action = abp.services.app.goodsAttribute.getGoodsAttributeList;
                        var paras = { goodsMould: params && params.id };
                        action(paras).done(function (res) {
                            self.cache = {};
                            $('#mouldCheck').empty();
                            if (res.items.length === 0) return;

                            var html = template('checkPanel', res);
                            var $table = $('<table></table>');
                            $('#mouldCheck').append(html).append($table)
                                .off('change')
                                .on('change', 'input[type=checkbox]', function (e) {
                                    var $sender = $(e.currentTarget),
                                        field = $sender.data("field"),
                                        uniqueid = $sender.data("unique-id"),
                                        val = $sender.val(),
                                        cache = self.cache[field];
                                    var selection = { id: uniqueid, val: val };

                                    if ($sender.prop("checked")) {
                                        cache.push(selection);
                                        var data = $.extend({}, self.cache);
                                        data[field] = selection;
                                        var rows = $.permutateArray(data);
                                        $table.bootstrapTable('append', rows);
                                    } else {
                                        for (var len = cache.length, i = len - 1 ; i >= 0; i--) {
                                            if (_.isEqual(selection, cache[i])) {
                                                cache.splice(i, 1);
                                            }
                                        }
                                        $table.bootstrapTable('remove', { field: field, values: [selection] });
                                    }
                                });

                            var columns = [
                                {
                                    title: "",
                                    searchable: false,
                                    formatter: function (value, row, index) { return index + 1; },
                                    align: "center",
                                    valign: "middle"
                                }
                            ];
                            $.each(res.items, function (index, value, array) {
                                columns.push({
                                    field: value.id,
                                    title: value.name,
                                    valign: "middle",
                                    formatter: function (value) { return value.val; }
                                });
                                self.cache[value.id] = [];
                            });
                            columns = columns.concat([
                                {
                                    field: '@("Quantity".ToCamelCase())',
                                    title: self.localize("Stock"),
                                    searchable: false,
                                    input: true,
                                    validate: function (val) {
                                        return /^(0|\+?[1-9][0-9]*)$/.test(val);
                                    }
                                },
                                {
                                    field: '@("Price".ToCamelCase())',
                                    title: self.localize("Price"),
                                    searchable: false,
                                    input: true,
                                    validate: function (val) {
                                        return /^\d+(\.\d+)?$/.test(val);
                                    }
                                },
                                {
                                    field: '@("SalePrice".ToCamelCase())',
                                    title: self.localize("SalePrice"),
                                    searchable: false,
                                    input: true,
                                    validate: function (val) {
                                        return /^\d+(\.\d+)?$/.test(val);
                                    }
                                },
                                {
                                    field: '@("BottomPrice".ToCamelCase())',
                                    title: self.localize("BottomPrice"),
                                    searchable: false,
                                    input: true,
                                    validate: function (val) {
                                        return /^\d+(\.\d+)?$/.test(val);
                                    }
                                }
                            ]);
                            self.table = $table.bootstrapTable({
                                toggle: "table",
                                striped: true,
                                keyEvents: true,
                                sortable: false,
                                columns: columns
                            });
                            self.table.parents(".bootstrap-table").hide();
                            self.table.on('post-body.bs.table', function (_, data) {
                                if (data.length === 0) {
                                    self.table.parents(".bootstrap-table").hide();
                                } else {
                                    self.table.parents(".bootstrap-table").show();
                                }
                            });
                        });
                    });
                },
                formSubmit: function () {
                    this.$form.submit(function (e) {
                        e.preventDefault();
                    });
                },
                binding: function () {
                    var self = this;
                    self.$box.on("click", '.btn', function (e) {
                        e.preventDefault();

                        var $sender = $(e.currentTarget);
                        var action = $.trim($sender.data("action"));
                        switch (action) {
                            case "submit":
                                self.submit();
                                break;
                        }
                    });
                },
                submit: function () {
                    var self = this;
                    abp.ui.setBusy(self.$box);
                    var data = self.$form.serializeFormToObject();
                    data["skus"] =
                        _.map(self.table.bootstrapTable("getData"), function (el) {
                            var attrs = _.map(_.filter(_.values(el), function (val) { return val instanceof Object; }), function (val) { return val.id; });
                            return $.extend({ attrvalues: attrs }, el);
                        });
                    self.service.createGoods(data)
                        .done(function () {
                            abp.message.success(self.localize("AddGoodsSucceed"))
                                .done(function () { location.href = "@Url.Action("list")"; });
                        })
                        .always(function () {
                            abp.ui.clearBusy(self.$box);
                        });
                }
            };

            $(function () { (new $$$()).init(); });
        }(jQuery);
    </script>
    <script id="checkPanel" type="text/html">
        {{each items as item}}
        <div class="panel panel-info">
            <div class="panel-heading">
                <div class="row">
                    <div class="col-md-4">{{item.name}}</div>
                    <div class="col-md-2 col-md-offset-6">
                        <a class="pull-right" href="@Url.Action("Edit","GoodsAttributes",new { Id=" " }){{item.id}}">
                            <i class="fa fa-plus"></i>
                            <span class="bold">@L("Add")</span>
                        </a>
                    </div>
                </div>
            </div>
            <div class="panel-body form-inline">
                {{each item.values as val}}
                <div class="input-group" style="padding-right:10px;padding-bottom:10px;">
                    <label class="input-group-addon input-group-check">
                        <input type="checkbox" data-field="{{item.id}}" data-unique-id="{{val.id}}" value="{{val.value}}">
                        <i class="input-box"></i>
                    </label>
                    <input type="text" class="form-control" value="{{val.value}}" readonly>
                </div>
                {{/each}}
            </div>
        </div>
        {{/each}}
    </script>
}
<ul class="content-nav">
    <li>
        <a href="@Url.Action("list")">@L("List")</a>
    </li>
    <li class="active">
        <a href="javascript:;">@L("Add")</a>
    </li>
</ul>
<div class="box box-success box-edge-all" data-dock="true">
    <form role="form">
        <div class="box-body">
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsSerialNo")</label>
                        <input name="SerialNo"
                               type="text"
                               class="form-control"
                               maxlength="@FutureGoodsItem.MaxSerialNoLength">
                    </div>
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsName")</label>
                        <input name="Name"
                               type="text"
                               class="form-control"
                               maxlength="@FutureGoodsItem.MaxNameLength">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsBrand")</label>
                        <input name="BrandId" data-toggle="list-modal"
                               data-title="@L("GoodsBrand")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsBrand.getGoodsBrandList"
                               data-columns="[{ field: 'name', title: '@L("GoodsBrand")' }]" />
                    </div>
                </div>
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsCategory")</label>
                        <input name="CategoryId" data-toggle="list-modal"
                               data-title="@L("GoodsCategory")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsCategory.getGoodsCategoryList"
                               data-columns="[{ field: 'name', title: '@L("GoodsCategory")' }]" />
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-5">
                    <div class="form-group">
                        <label>@L("GoodsMould")</label>
                        <input name="MouldId" data-toggle="list-modal"
                               data-title="@L("GoodsMould")"
                               data-display-member="name"
                               data-service="abp.services.app.goodsMould.getGoodsMouldList"
                               data-columns="[{ field: 'name', title: '@L("GoodsCategory")' }]"
                               data-render="mouldCheck" />
                    </div>
                </div>
            </div>
            <div class="row">
                <div id="mouldCheck" class="col-sm-10"></div>
            </div>
        </div>
        <div class="box-footer">
            <a class="btn btn-primary" href="javascript:;" data-action="submit">
                <i class="fa fa-check"></i>
                @L("Submit")
            </a>
        </div>
    </form>
</div>